<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <title>PBOtest H5 Client</title>
  <style>
    body { font-family: Arial, sans-serif; margin: 12px; }
    #messages { border:1px solid #ccc; height:300px; overflow:auto; padding:6px; margin-bottom:8px; }
    input, select, button { margin-right:6px; }
  </style>
</head>
<body>
  <h1>PBOtest H5 Client</h1>

  <main style="max-width: 600px;">
    <details open>
      <summary>Login</summary>
      <label>Server: <input id="server" value="localhost:8080"></label>
      <label>Room: <input id="room" value="room1"></label>
      <label>Nickname: <input id="nickname" value="user"></label>
      <label>Seat:
        <select id="seat">
          <option value="spectator">spectator</option>
          <option value="player1">player1</option>
          <option value="player2">player2</option>
        </select>
      </label>
      <button id="connectBtn">Connect</button>
      <button id="quitBtn" disabled>Quit</button>
    </details>

    <div id="messages"></div>

    <details open>
      <summary>Prepare</summary>
      <label>Mode:
        <select id="mode">
          <option value="single">single</option>
        </select>
      </label>
      <label>Team: </label><button id="prepareBtn">Prepare</button>
      <textarea id="logArea" style="width:100%;height:150px;">图图犬 摇手指</textarea>
    </details>

    <details open>
      <summary>Chat</summary>
      <input id="chatInput" placeholder="Type chat..." style="width:60%">
      <button id="sendChatBtn" disabled>Send</button>
    </details open>
  </main>

  <script>
    let ws = null;
    let connected = false;
    const messagesEl = document.getElementById('messages');
    const connectBtn = document.getElementById('connectBtn');
    const quitBtn = document.getElementById('quitBtn');
    const sendChatBtn = document.getElementById('sendChatBtn');
    const prepareBtn = document.getElementById('prepareBtn');

    function log(text, meta) {
      const d = document.createElement('div');
      d.innerHTML = text;
      messagesEl.appendChild(d);
      messagesEl.scrollTop = messagesEl.scrollHeight;
    }

    connectBtn.onclick = (_) => {
      const room = document.getElementById('room').value.trim();
      const nickname = document.getElementById('nickname').value.trim();
      const seat = document.getElementById('seat').value;
      if (!room || !nickname) { alert('room and nickname required'); return; }

      ws = new WebSocket('ws://'+document.getElementById('server').value.trim());

      ws.addEventListener('open', () => {
        log('WebSocket connected');
        // Send login object required by server
        ws.send(JSON.stringify({
          secret: 'PBOtest',
          room: room,
          nickname: nickname,
          seat: seat,
          version: '0.1-h5'
        }));
        connected = true;
        connectBtn.disabled = true;
        quitBtn.disabled = false;
        sendChatBtn.disabled = false;
        prepareBtn.disabled = false;
        //startHeartbeat();
      });

      ws.addEventListener('message', (ev) => {
        let data = ev.data;
        try {
          if (typeof data === 'string' && (data[0] === '{' || data[0] === '[')) data = JSON.parse(data);
        } catch (e) {
          log('Received non-json message: ' + ev.data);
          return;
        }

        // handle server messages
        if (data.secret) {
          log('Server: ' + (data.message || 'welcome'), 'version:' + (data.serverVersion || data.version || 'unknown'));
          return;
        }

        // standard heads from server: chat, gameStart, userQuit, userClosed, ...
        switch (data.head) {
          case 'chat':
            log((data.nickname ? ('['+data.nickname+'] ') : '') + data.message, 'chat');
            break;
          case 'game.start':
            log('PokemonBattleOnline-test v0.10')
            log('对战模式：' + (data.mode == 'single'? '单打': '未知'))
            log('对战规则：催眠条款')
            log('对战开始！')
            break;
          case 'game.sendOut':
            log(data.nickname + '放出了' + data.pokemonname + '！', 'game.sendOut')
            break;
          case 'userQuit':
            log('User quit: ' + data.nickname, 'userQuit')
            break;
          case 'userClosed':
            log('User disconnected: ' + data.nickname, 'userClosed')
            break;
          default:
            log('Unknown message: ' + JSON.stringify(data))
        }
      });

      ws.addEventListener('close', () => {
        log('WebSocket closed');
        connected = false;
        connectBtn.disabled = false;
        quitBtn.disabled = true;
        sendChatBtn.disabled = true;
        prepareBtn.disabled = true;
      });

      ws.addEventListener('error', (e) => {
        console.error('ws error', e);
        log('WebSocket error');
      });
    }

    function send(obj) {
      if (!ws || ws.readyState !== WebSocket.OPEN) { log('Not connected'); return; }
      ws.send(JSON.stringify(obj));
    }

    document.getElementById('sendChatBtn').addEventListener('click', () => {
      const text = document.getElementById('chatInput').value.trim();
      if (!text) return;
      send({ head: 'chat', message: text });
      // locally echo
      log('[me] ' + text, 'chat');
      document.getElementById('chatInput').value = '';
    });

    prepareBtn.onclick = (_) => {
      //const team = document.getElementById('team').value;
      const mode = document.getElementById('mode').value;
      let team = [{
        index: 0,
        name: '图图犬',
        number: 235,
        form: 0,
        lv: 100,
        gender: 'm',
        iv: [31,31,31,31,31,31],
        ev: [252,252,4,0,0,0],
        item:0,
        abilityIndex: 0,
        nature: 0,
        happiness: 255,
        moves: [118], //摇手指
        movesPP: [2],
      }]
      send({ head: 'prepare', team: team, mode: mode });
      log('Prepared: team=' + team[0].name + ' mode=' + mode, 'prepare');
    }

    quitBtn.addEventListener('click', () => {
      send({ head: 'quit' });
      // close locally
      if (ws) ws.close();
    });

    // quick auto-connect for dev
    // connect();
  </script>
</body>
</html>